package cs419.magnusmi.trackitcs;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import org.json.JSONException;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class SignUp extends Activity {
    /**
     * The default email to populate the email field with.
     */
    public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserSignupTask mAuthTask = null;

    // Values for email and password at the time of the login attempt.
    private String user;
    private String pass;
    private String fname;
    private String lname;
    private String email;
    private String passClone;

    // UI references.
    private EditText unamePrompt;
    private EditText passwordPrompt;
    private EditText passAgainPrompt;
    private EditText fnamePrompt;
    private EditText lnamePrompt;
    private EditText emailPrompt;
    private View mLoginFormView;
    private View mLoginStatusView;
    private TextView mLoginStatusMessageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_sign_up);
        setupActionBar();

        // Set up the login form.
        email = getIntent().getStringExtra(EXTRA_EMAIL);
        emailPrompt = (EditText) findViewById(R.id.emailPrompt);
        emailPrompt.setText(email);

        unamePrompt = (EditText) findViewById(R.id.unamePrompt);
        fnamePrompt = (EditText) findViewById(R.id.fnamePrompt);
        lnamePrompt = (EditText) findViewById(R.id.lnamePrompt);
        emailPrompt = (EditText) findViewById(R.id.emailPrompt);
        passwordPrompt = (EditText) findViewById(R.id.password);
        passAgainPrompt = (EditText) findViewById(R.id.password1);

        mLoginFormView = findViewById(R.id.login_form);
        mLoginStatusView = findViewById(R.id.login_status);
        mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

        findViewById(R.id.registerBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
    }

    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupActionBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            // Show the Up button in the action bar.
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            // This ID represents the Home or Up button. In the case of this
            // activity, the Up button is shown. Use NavUtils to allow users
            // to navigate up one level in the application structure. For
            // more details, see the Navigation pattern on Android Design:
            //
            // http://developer.android.com/design/patterns/navigation.html#up-vs-back
            //
            // TODO: If Settings has multiple levels, Up should navigate up
            // that hierarchy.
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.sigun_up, menu);
        return true;
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    public void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }

        // Reset errors.
        unamePrompt.setError(null);
        passwordPrompt.setError(null);
        passAgainPrompt.setError(null);
        fnamePrompt.setError(null);
        lnamePrompt.setError(null);
        emailPrompt.setError(null);

        // Store values at the time of the login attempt.

        user = unamePrompt.getText().toString();
        pass = passwordPrompt.getText().toString();
        passClone = passAgainPrompt.getText().toString();
        fname = fnamePrompt.getText().toString();
        lname = lnamePrompt.getText().toString();
        email = emailPrompt.getText().toString();

        //validate form
        boolean cancel = false;

        //array of Views to highlight any invalid input
        View[] focusViews = new View[9];
        for (int i = 0; i < focusViews.length; i++){
            focusViews[i] = null;
        }

        //check for valid username
        if (TextUtils.isEmpty(user)) {
            unamePrompt.setError(getString(R.string.error_field_required));
            focusViews[0] = unamePrompt;
            cancel = true;
        } else if (user.length() < 6) {
            unamePrompt.setError(getString(R.string.error_invalid_user));
            focusViews[0] = unamePrompt;
            cancel = true;
        }

        // Check for a valid password.
        if (TextUtils.isEmpty(pass)) {
            passwordPrompt.setError(getString(R.string.error_field_required));
            focusViews[1] = passwordPrompt;
            cancel = true;
        } else if (pass.length() < 6) {
            passwordPrompt.setError(getString(R.string.error_invalid_password));
            focusViews[1] = passwordPrompt;
            cancel = true;
        }
        //check for matching passwords
        if (TextUtils.isEmpty(passClone)) {
            passAgainPrompt.setError(getString(R.string.error_field_required));
            focusViews[2] = passAgainPrompt;
        }
        if (!pass.equals(passClone)){
            passwordPrompt.setError(getString(R.string.error_password_mismatch));
            passAgainPrompt.setError(getString(R.string.error_password_mismatch));
            focusViews[3] = passwordPrompt;
            focusViews[4] = passAgainPrompt;
            cancel = true;
        }
        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            emailPrompt.setError(getString(R.string.error_field_required));
            focusViews[5] = emailPrompt;
            cancel = true;
        } else if (!email.contains("@")) {
            emailPrompt.setError(getString(R.string.error_invalid_email));
            focusViews[6] = emailPrompt;
            cancel = true;
        }
        //check that first name, last name are present
        if (TextUtils.isEmpty(fname)) {
            fnamePrompt.setError(getString(R.string.error_field_required));
            focusViews[7] = fnamePrompt;
            cancel = true;
        }
        if (TextUtils.isEmpty((lname))){
            lnamePrompt.setError(getString(R.string.error_field_required));
            focusViews[8] = lnamePrompt;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            // set focus to first field.  Others are clickable
            for (int i = 0; i < focusViews.length; i++){
                if (focusViews[i] != null){
                    focusViews[i].requestFocus();
                    break;
                }
            }
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            mLoginStatusMessageView.setText(R.string.login_progress_signing_up);
            showProgress(true);
            mAuthTask = new UserSignupTask();
            mAuthTask.execute((Void) null);
        }
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginStatusView.setVisibility(View.VISIBLE);
            mLoginStatusView.animate()
                    .setDuration(shortAnimTime)
                    .alpha(show ? 1 : 0)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
                        }
                    });

            mLoginFormView.setVisibility(View.VISIBLE);
            mLoginFormView.animate()
                    .setDuration(shortAnimTime)
                    .alpha(show ? 0 : 1)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                        }
                    });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserSignupTask extends AsyncTask<Void, Void, Boolean> {
        private String response = "";

        @Override
        protected Boolean doInBackground(Void... params) {
            String register = "http://web.engr.oregonstate.edu/~cohenad/cs419/index.php/register";

            JSONParser jsonParser = new JSONParser();
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            parameters.add(new BasicNameValuePair("user", user));
            parameters.add(new BasicNameValuePair("pass", pass));
            parameters.add(new BasicNameValuePair("fname", fname));
            parameters.add(new BasicNameValuePair("lname", lname));
            parameters.add(new BasicNameValuePair("email", email));

            JSONObject json = jsonParser.makeHttpRequest(register, "POST", parameters);


                Boolean errors = true;
                try{
                    response = json.getString("message");
                    errors = json.getBoolean("error");
                }
                catch (JSONException e) {
                    errors = true;
                }

            return errors;
        }

        @Override
        protected void onPostExecute(final Boolean errors) {
            mAuthTask = null;
            showProgress(false);

            boolean success = !errors;  //no errors = success

            if (success) {
                Context context = getApplicationContext();
                int duration = Toast.LENGTH_SHORT;
                Toast toast = Toast.makeText(context, response, duration);
                toast.show();
                finish();
            } else {
                Context context = getApplicationContext();
                int duration = Toast.LENGTH_SHORT;
                Toast toast = Toast.makeText(context, response, duration);
                toast.show();
                //finish();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}
